//
//  SignInViewController.m
//  Anyair
//
//  Created by karlcool on 14-5-12.
//  Copyright (c) 2014年 Karlcool. All rights reserved.
//

#import "SignInViewController.h"
#import "Regular.h"
#import "IQKeyBoardManager.h"

@interface SignInViewController ()

@end

@implementation SignInViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (!IPHONE_5) {
        [IQKeyBoardManager installKeyboardManager];
        [IQKeyBoardManager enableKeyboardManger];
    }
    self.view.backgroundColor = AIR_GRAY;
    
    LRTopBar *topBar = [[LRTopBar alloc]initWithTitle:@"注册" AndLeftText:@"取消" AndRightText:@"提交"];
    topBar.delegete = self;
    [self.view addSubview:topBar];
    
    UIView *phoneBackView = [[UIView alloc]initWithFrame:CGRectMake(-0.5, 100, 321, 100)];
    phoneBackView.backgroundColor = [UIColor whiteColor];
    phoneBackView.layer.borderColor = BREAKLINE_GRAY.CGColor;
    phoneBackView.layer.borderWidth = 0.5;
    [self.view addSubview:phoneBackView];
    
    phoneText = [[UITextField alloc]initWithFrame:CGRectMake(25, 10, 245, 30)];
    phoneText.backgroundColor = [UIColor clearColor];
    phoneText.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    phoneText.placeholder = @"手机号";
    phoneText.keyboardType = UIKeyboardTypePhonePad;
    [phoneText addTarget:self action:@selector(didEndExit:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [phoneBackView addSubview:phoneText];
    
    
    authCodeText = [[UITextField alloc]initWithFrame:CGRectMake(25, 60, 180, 30)];
    authCodeText.backgroundColor = [UIColor clearColor];
    authCodeText.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    authCodeText.placeholder = @"验证码";
    [authCodeText addTarget:self action:@selector(didEndExit:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [phoneBackView addSubview:authCodeText];

    UIView *breakLine = [[UIView alloc]initWithFrame:CGRectMake(25, 50, 295, 1)];
    breakLine.backgroundColor = BREAKLINE_GRAY;
    [phoneBackView addSubview:breakLine];
    
    UIView *breakLine2 = [[UIView alloc]initWithFrame:CGRectMake(243, 55, 1, 40)];
    breakLine2.backgroundColor = BREAKLINE_GRAY;
    [phoneBackView addSubview:breakLine2];
    
    authBtn = [[UIButton alloc]initWithFrame:CGRectMake(260, 62, 50, 30)];
    authBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [authBtn setTitle:@"发送" forState:UIControlStateNormal];
    [authBtn setTitleColor:AIR_GREEN forState:UIControlStateNormal];
    [authBtn setTitleColor:AIR_GREEN_DEEP forState:UIControlStateHighlighted];
    [authBtn addTarget:self action:@selector(sendAuth:) forControlEvents:UIControlEventTouchUpInside];
    [phoneBackView addSubview:authBtn];
    
    
    UIView *passwordBackView = [[UIView alloc]initWithFrame:CGRectMake(-0.5, 230, 321, 100)];
    passwordBackView.backgroundColor = [UIColor whiteColor];
    passwordBackView.layer.borderColor = BREAKLINE_GRAY.CGColor;
    passwordBackView.layer.borderWidth = 0.5;
    [self.view addSubview:passwordBackView];
    
    passwordText = [[UITextField alloc]initWithFrame:CGRectMake(25, 10, 245, 30)];
    passwordText.backgroundColor = [UIColor clearColor];
    passwordText.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    passwordText.placeholder = @"密码";
    passwordText.secureTextEntry = YES;
    [passwordText addTarget:self action:@selector(didEndExit:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [passwordBackView addSubview:passwordText];
    
    
    surePasswordText = [[UITextField alloc]initWithFrame:CGRectMake(25, 60, 245, 30)];
    surePasswordText.backgroundColor = [UIColor clearColor];
    surePasswordText.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    surePasswordText.placeholder = @"确认密码";
    surePasswordText.secureTextEntry = YES;
    [surePasswordText addTarget:self action:@selector(didEndExit:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [passwordBackView addSubview:surePasswordText];
    
    UIImageView *passwordImageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 40, 40)];
    [passwordBackView addSubview:passwordImageView];
    
    UIImageView *surePasswordImageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 55, 40, 40)];
    [passwordBackView addSubview:surePasswordImageView];
    
    UIView *breakLine3 = [[UIView alloc]initWithFrame:CGRectMake(25, 50, 295, 1)];
    breakLine3.backgroundColor = BREAKLINE_GRAY;
    [passwordBackView addSubview:breakLine3];
    
    authCount = 90;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setDefultBtn) name:@"goBack" object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - 顶栏委托

#pragma mark - 取消注册
- (void)clickLeft:(UIButton*)sender {
    [IQKeyBoardManager disableKeyboardManager];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
#pragma mark - 执行注册
- (void)clickRight:(UIButton*)sender {
    if (![Regular validateMobile:phoneText.text]) {
        UIAlertView *phoneAlert = [[UIAlertView alloc]initWithTitle:@"错误" message:@"手机号输入有误" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [phoneAlert show];
        return;
    }
    if (passwordText.text.length==0) {
        UIAlertView *passwordAlert = [[UIAlertView alloc]initWithTitle:@"错误" message:@"密码不能为空" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [passwordAlert show];
        return;
    }
    if (![Regular validatePassword:passwordText.text]) {
        UIAlertView *passwordAlert = [[UIAlertView alloc]initWithTitle:@"错误" message:@"密码必须为6到16为数字和字母" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [passwordAlert show];
        return;
    }
    if (![passwordText.text isEqualToString:surePasswordText.text]) {
        UIAlertView *passwordAlert = [[UIAlertView alloc]initWithTitle:@"错误" message:@"两次密码不一致" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [passwordAlert show];
        return;
    }
    if (![LRTools checkNetWork]) {
        UIAlertView *failAlert = [[UIAlertView alloc]initWithTitle:@"网络不可用" message:@"请检查你的网络" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [failAlert show];
        return;
    }
    //注册操作
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_LOW ,0),^{
        
        NSDictionary *resposeDic = [[LRHttpManager createHttpManager]signInUserByPhone:phoneText.text AndPassword:passwordText.text AndVerifycode:authCodeText.text];
        dispatch_async (dispatch_get_main_queue(),^{
            
            if ([[resposeDic objectForKey:@"code"] integerValue]==0) {
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                [self.view addSubview:shortHub];
                [shortHub setLabelText:@"注册成功"];
                [shortHub setMode:MBProgressHUDModeText];
                [shortHub hide:YES afterDelay:1];
                [shortHub show:YES];
                [[NSUserDefaults standardUserDefaults]setObject:phoneText.text forKey:@"userPhone"];
                [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"isLogIn"];
                [LRUserManager createManager].userPhone = phoneText.text;
                [self dismissViewControllerAnimated:NO completion:^{
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"logInSuccess" object:nil];
                }];
                
            } else if (((NSString*)[resposeDic objectForKey:@"message"]).length!=0) {
                MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                [self.view addSubview:shortHub];
                [shortHub setLabelText:[resposeDic objectForKey:@"message"]];
                [shortHub setMode:MBProgressHUDModeText];
                [shortHub hide:YES afterDelay:1];
                [shortHub show:YES];
            } else {
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                [self.view addSubview:shortHub];
                [shortHub setLabelText:@"注册失败,请稍后再试"];
                [shortHub setMode:MBProgressHUDModeText];
                [shortHub hide:YES afterDelay:1];
                [shortHub show:YES];
            }
            
        });
    });
}

#pragma mark - 发送验证码
- (void)sendAuth:(UIButton *)sender {
    if (![Regular validateMobile:phoneText.text]) {
        UIAlertView *phoneAlert = [[UIAlertView alloc]initWithTitle:@"错误" message:@"手机号输入有误" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [phoneAlert show];
        return;
    }
    
    NSDate *lastDate = [[NSUserDefaults standardUserDefaults]objectForKey:@"lastAuthTime"];
    NSTimeInterval lastAuthTime = [[NSDate date]timeIntervalSinceDate:lastDate];
    if (![LRTools checkNetWork]) {
        UIAlertView *failAlert = [[UIAlertView alloc]initWithTitle:@"网络不可用" message:@"请检查你的网络" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [failAlert show];
        return;
    }
    if (lastAuthTime<=90) {
        MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:shortHub];
        [shortHub setLabelText:@"发送过于频繁"];
        [shortHub setMode:MBProgressHUDModeText];
        [shortHub hide:YES afterDelay:1];
        [shortHub show:YES];

    } else {
        //再次发送验证码
        dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_LOW ,0),^{
            NSDictionary *resposeDic = [[LRHttpManager createHttpManager]sendAuthToPhone:phoneText.text AndType:@"0"];
            
            dispatch_async (dispatch_get_main_queue(),^{
                
                if ([[resposeDic objectForKey:@"code"] integerValue]==0) {
                    [authBtn setTitle:@"90s" forState:UIControlStateNormal];
                    authTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sendAgain) userInfo:nil repeats:YES];
                    MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                    [self.view addSubview:shortHub];
                    [shortHub setLabelText:@"验证码已发送到您手机"];
                    [shortHub setMode:MBProgressHUDModeText];
                    [shortHub hide:YES afterDelay:1];
                    [shortHub show:YES];
                    [[NSUserDefaults standardUserDefaults]setObject:[NSDate date] forKey:@"lastAuthTime"];
                }  else if ([[resposeDic objectForKey:@"message"] isEqualToString:@"该手机号码已经注册"]) {
                    MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                    [self.view addSubview:shortHub];
                    [shortHub setLabelText:[resposeDic objectForKey:@"该手机号码已经注册"]];
                    [shortHub setMode:MBProgressHUDModeText];
                    [shortHub hide:YES afterDelay:1];
                    [shortHub show:YES];
                } else {
                    MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                    [self.view addSubview:shortHub];
                    [shortHub setLabelText:@"验证码发送失败,请稍后再试"];
                    [shortHub setMode:MBProgressHUDModeText];
                    [shortHub hide:YES afterDelay:1];
                    [shortHub show:YES];
                }

            });
        });
        
    }
}


#pragma mark - 再次发送倒计时

- (void)sendAgain {
    if (authCount<=0) {
        [authBtn setTitle:@"发送" forState:UIControlStateNormal];
        [authTimer invalidate];
        authTimer = nil;
        authCount = 90;
        authBtn.userInteractionEnabled = YES;
    } else {
        authCount--;
        [authBtn setTitle:[NSString stringWithFormat:@"%lis",(long)authCount] forState:UIControlStateNormal];
        authBtn.userInteractionEnabled = NO;
    }
    
}

- (void)setDefultBtn {
    [authBtn setTitle:@"发送" forState:UIControlStateNormal];
    authBtn.userInteractionEnabled = YES;
}

#pragma mark - 释放键盘
- (void)didEndExit:(UITextField *)sender {
    [sender resignFirstResponder];
}
@end
